<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>04_阻止事件传播</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      .out {
        width: 500px;
        height: 500px;
        background-color: pink;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .center {
        width: 300px;
        height: 300px;
        background-color: skyblue;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .inner {
        width: 100px;
        height: 100px;
        background-color: purple;
      }
    </style>
  </head>

  <body>
    <div class="out">
      <div class="center">
        <div class="inner"></div>
      </div>
    </div>

    <!-- 
    stop 停止 start开始 begin开始 pause暂停
    propagation 传播
    cancel 取消 confirm确认
    bubble 冒泡 capture捕获
     -->
    <script>
      /* 找出元素 */
      var inner = document.querySelector(".inner");
      var center = document.querySelector(".center");
      var out = document.querySelector(".out");

      function outHandler(e) {
        console.log("outHandler");

        // 在outHandler中阻断事件传播
        // e.stopPropagation();
        // console.log("事件传播中断");
      }
      function centerHandler(e) {
        console.log("centerHandler");
      }
      function innerHandler(e) {
        console.log("innerHandler");

        e.stopPropagation();
        console.log("事件传播中断");
      }

      /* 事件仅由out处理 */
      /* 使用冒泡：不要给inner和center添加事件处理器 */
      // out.addEventListener("click",outHandler,false)

      /* 使用捕获：在outHandler中阻断事件传播 */
      // out.addEventListener("click",outHandler,true)
      // center.addEventListener("click",centerHandler,true)
      // inner.addEventListener("click",innerHandler,true)

      /* inner out 先后处理 */
      // 解决方案：冒泡 + 添加inner+out两级处理器 + 在out中断
      //   out.addEventListener("click", outHandler, false);
      //   inner.addEventListener("click", innerHandler, false);

      /* out center inner 三级先后处理 */
      // 解决方案：捕获 + 添加inner+center+out三级处理器 + 在inner中断
      out.addEventListener("click", outHandler, true);
      center.addEventListener("click", centerHandler, true);
      inner.addEventListener("click", innerHandler, true);
    </script>
  </body>
</html>
